#/usr/bin/env python
# -*- coding: utf-8 -*-

'''
Created on 2011-8-02

主要用于从网站上爬取信息后，抽取页面信息；

@author: zhongfeng
'''


from pageparser import *

class IcsonAllSortParser(RootCatagoryPageParser):
    '''
            从http://sz.icson.com/portal.html获取所有的分类信息，
            组合成ObuyUrlSummary
    '''   
    mainHost = 'http://sz.icson.com/'
    def __init__(self, dataStr, rootUrlSummary, include=None, exclude=None):
        super(IcsonAllSortParser, self).__init__(dataStr, rootUrlSummary, include, exclude) 
                             
    def getBaseSort3UrlSums(self):       
        finalUrlList = []
        allSort = self.soup.find(attrs={'id':'protal_list'})
        for t in allSort.findAll(name='div',attrs={'class':'item_hd'}):#一级分类
            name,url = ParserUtils.parserTag_A(t.find(name='a'))
            sort_1_urlsum = self.buildSort_N(url, name, self.rootUrlSummary, isCrawle=False)
            sort_2 = t.findNextSibling(name='div',attrs={'class':'item_bd'})
            for tt in sort_2(name='dl'):#二级分类
                name = tt.dt.getText()
                url = ''.join((self.mainHost,name))
                sort_2_urlsum = self.buildSort_N(url, name, sort_1_urlsum, isCrawle=False)
                for ttt in tt.findAll(name='a'):#三级分类
                    name, url = ParserUtils.parserTag_A(ttt)
                    sort_3_urlsum = self.buildSort_N(url, name, sort_2_urlsum)
                    finalUrlList.append(sort_3_urlsum)
        return finalUrlList  
        
class IcsonSort3PageParser(Sort3PageParser):
    '''
          三级页面解析类
    '''    
    def __init__(self, dataStr, rootUrlSummary, include=None, exclude=None):
        super(IcsonSort3PageParser, self).__init__(dataStr, rootUrlSummary, include, exclude)
    
    def nextPageUrlPattern(self):
        urlSegs = self.rootUrlSummary.url.rsplit('.', 1)
        pageSeg = '-0-6-10-20-0-{}--'
        return '%s%s.%s' % (urlSegs[0].replace('--------',''), pageSeg, urlSegs[1])
    
    def getTotal(self):
        nextSeg = self.soup.find(name='a',attrs={'class':'page-next'})
        if nextSeg != None:
            t = nextSeg.findPreviousSibling(name='a').getText()
            return int(t)
        else:
            return 1
    
    def parserPageInfos(self):      
        plist = self.soup.find(name='li',attrs={'class':'item_list'})
        resultList = []
        for prod in plist:
            pNameSeg = prod.find(attrs={'class':'wrap_info'})
            pName,url = ParserUtils.parserTag_A(pNameSeg.a)
            adWords = pNameSeg.find(name='p',attrs={'class':'hot'})
            pid = url.rsplit('-',1)[-1].split('.')[0]
            t = prod.find(attrs={'class':'price_icson'})
            if t != None:
                currentPrice = ParserUtils.getPrice(t.getText())
            else:
                currentPrice = 0.00
            prodDetail = ProductDetails(productId=pid, privPrice = currentPrice,
                                        name=pName, adWords=adWords)
            resultList.append(prodDetail)
        return resultList

class IcsonSort4PageParser(IcsonSort3PageParser):
    '''
          分类四级页面为列表页面，只抽取Product信息
    '''
    def __init__(self, dataStr, rootUrlSummary, include=None, exclude=None):
        super(IcsonSort4PageParser, self).__init__(dataStr, rootUrlSummary, include, exclude)
        
    def parserSubUrlSums(self):
        pass
    
            
''' test '''
import os
curModDir = os.path.dirname(os.path.abspath(__file__))
testFilePath = os.path.join(curModDir,'test_resources')
def testIcsonAllSortPage():
    fileName = os.path.join(testFilePath,'dangcat.html')
    with open(fileName, 'r') as fInput:
        content = fInput.read()

    rootUrlSum = ObuyUrlSummary(url=r'http://category.dangdang.com/', name='Icson')
    pserver  = ObuyUrlSummary(url = r'http://category.dangdang.com/list?cat=4001976', 
                               name='奶粉',catagoryLevel = 2)
    firstPage = IcsonAllSortParser(content, rootUrlSum,include = [pserver])
    for sort_3 in firstPage.parserSubUrlSums():       
        for index, urlsum in enumerate(sort_3.parentPath):
            print urlsum.name
        print sort_3.name,sort_3.url ,sort_3.catagoryLevel 

def testSort3Page():    
    fileName = os.path.join(testFilePath,'dangdang_2011-08-19_13-03-03.html')
    with open(fileName, 'r') as fInput:
        content = fInput.read()
    sort_3_urlsum = ObuyUrlSummary(url=r'http://category.dangdang.com/list?cat=4001011&store=eq0',
                                    parentPath=[('test')], catagoryLevel=3)
    sort3Page = IcsonSort3PageParser(content, sort_3_urlsum)
    for sort_4 in sort3Page.getSort4PageUrlSums():
        print sort_4.url

def testSort3Details():
    fileName = os.path.join(testFilePath,'dangdang_2011-08-19_13-03-03.html')
    with open(fileName, 'r') as fInput:
        content = fInput.read()
    sort_3_urlsum = ObuyUrlSummary(url=r'http://category.dangdang.com/list?cat=4001011&store=eq0', 
                                   parentPath=[('test')], catagoryLevel=3)
    sort3Page = IcsonSort3PageParser(content, sort_3_urlsum)  
    for product in sort3Page.parserPageInfos():
        print product.logstr()

def testRegx():
    regx = u'共([0-9]*)页'
    p = re.compile(regx)
    fileName = os.path.join(testFilePath,'4001011.html')
    with open(fileName, 'r') as fInput:
        content = fInput.read()
    soup = BeautifulSoup(content)
    s = soup.find(name='span',attrs = {'id':'all_num'}).getText()
    content = content.decode('gb18030','ignore')
    print p.search(s).group(1)

if __name__ == '__main__':
    #testRegx()
    #testIcsonAllSortPage()
    testSort3Page()
    testSort3Details()

    
    
